package com.ciei.dpagm.shiro;


import com.ciei.dpagm.entity.Users;
import com.ciei.dpagm.service.RightService;
import com.ciei.dpagm.service.RoleService;
import com.ciei.dpagm.service.UsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


/**
 * 自定义身份认证与授权Realm
 *
 * @author kiho
 * @date 2022/11/11
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UsersService usersService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RightService rightService;

    /**
     * 获取授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Users currentUser = (Users) principals.getPrimaryPrincipal();
        Users user = usersService.loadByUsernameAndPassword(currentUser.getLoginName(), currentUser.getPassword());
        if (user != null) {
            Set<String> roleCodeSet = roleService.getRoleCodeSet(user.getUserId());
            authorizationInfo.setRoles(roleCodeSet);
            Set<String> rightCodeSet = rightService.getRightCodeSet(user.getUserId());
            authorizationInfo.setStringPermissions(rightCodeSet);
        }
        return authorizationInfo;
    }

    /**
     * 获取身份认证信息，当前为用户名密码认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        // 身份验证
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        Users user = usersService.loadByUsernameAndPassword(token.getUsername(), new String(token.getPassword()));
        if (user == null) {
            throw new AuthenticationException("用户名或者密码错误");
        } else if (null == user.getLocked()) {
            // null不可能，数据库有误
            throw new DisabledAccountException("该账户尚不可用");
        } else if (1 == user.getLocked()) {
            // 停用状态
            throw new DisabledAccountException("该用户已停用");
        } else if (3 == user.getLocked()) {
            // 锁定状态
            throw new LockedAccountException("该用户已被锁定");
        } else if (4 == user.getLocked()) {
            // 删除状态
            throw new AccountException("该用户不存在");
        }
        return new SimpleAuthenticationInfo(user, token.getPassword(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

}

